<?php
namespace Application\Api\Controller;

class MessageCode extends Base
{

    public function sendAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'imageName') || notSetOrEmpty($data, 'imageCode') || notSetOrEmpty($data, 'phone')){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        $imageName = $data['imageName'];
        $imageCode = $data['imageCode'];
        $phone = $data['phone'];
        if(!isPhone($phone)){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        /*图片验证码是否正确*/
        $cacheCommon = $this->get(CACHE_COMMON);
        $code = $cacheCommon->getData($imageName);
        if(!checkValidCode($code, $imageCode)){
            $this->sendFail('VALID_CODE_ERROR');
            return false;
        }
        /*频率检测*/
        $ip = '127.0.0.1';
        $serviceMessageCode = $this->get(SERVICE_MESSAGECODE);
        if(!$serviceMessageCode->notApiLimit($ip, $phone)){
            $this->sendFail('API_LIMIT_ERROR');
            return false;
        }
        /*发送*/
        $parameter = [
            'code' => $serviceMessageCode->getCode($phone)
        ];
        $result = $serviceMessageCode->send($phone, 'test', $parameter);
        if(isset($result['Code']) && $result['Code'] == 'OK'){
            $serviceMessageCode->save($ip, $phone, $code);
            $this->sendSuccess();
        }
        else{
            $this->sendFail();
        }
    }

}